﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Kaskelot.SP.Model.Contracts;
using Kaskelot.SP.Services;
using Kaskelot.SP.Core;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;
using System.Collections.Generic;
using System.Linq;

namespace Kaskelot.SP.UI.CONTROLTEMPLATES.Kaskelot.SP.UI.Forms
{
    public partial class BlankettForm : BaseForm, IForm
    {
        public string Id { get; set; }
        public string ParentId { get; set; }
        public Blankett Current { get; set; }
        private IEnumerable<Falt> CurrentFaltList { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
                return;

            using (AdminService svc = new AdminService())
            {
                if (Id.IsGuid())
                    Current = svc.GetBlankett(new Guid(Id));

                if (Current == null)
                {
                    Current = new Blankett();
                    CurrentFaltList = new List<Falt>();
                }
                else
                {
                    CurrentFaltList = svc.GetFaltForBlankett(Current.Id);
                }

                IList<ListItem> sourceItems = new List<ListItem>();
                IEnumerable<Falt> allaFalt = svc.GetAllaFalt().Except(CurrentFaltList);

                foreach (Falt f in allaFalt)
                {
                    sourceItems.Add(new ListItem
                    {
                        Text = f.Namn,
                        Value = f.Id.ToString(),
                        Selected = false
                    });
                }

                foreach (Falt f in CurrentFaltList)
                {
                    sourceItems.Add(new ListItem
                    {
                        Text = f.Namn,
                        Value = f.Id.ToString(),
                        Selected = true
                    });
                }

                FaltRepeater.DataSource = sourceItems;
                FaltRepeater.DataBind();


                BlankettTypRepeater.DataSource = Enum.GetValues(typeof(Stockholm.SOA.Kaskelot.WCF.DataContracts.BlankettTyp)).Cast<Stockholm.SOA.Kaskelot.WCF.DataContracts.BlankettTyp>().Select(t => new
                {
                    ID = (int)t,
                    Name = t.ToString()
                });
                BlankettTypRepeater.DataBind();
            }
        }

        public string GetItemSelected(bool selected)
        {
            if (selected)
                return "selected=\"selected\"";
            else
                return String.Empty;
        }
    }
}
